package com.tanhua.server.service;

import com.tanhua.commons.pojo.IMessage;
import com.tanhua.commons.template.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mogo.RecommendUser;
import com.tanhua.domain.mogo.UserLocationDTO;
import com.tanhua.domain.vo.NearUserVO;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.RecommendUserQueryVO;
import com.tanhua.domain.vo.RecommendUserVO;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TanhuaService  {
    @Reference
    private UserLocationApi userLocationApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private RecommendUserApi recommendUserApi;

    public ResponseEntity todayBest() {
    //获取当前用户
        Long userId = UserHolder.getUserId();
        //查询当前用户缘分值最高的人 得到RecommendUser
        RecommendUser recommendUser = recommendUserApi.findMaxScoreUser(userId);
           if (recommendUser==null){
               //如果没有推荐的人 就给一个默认值
                recommendUser = new RecommendUser();
                recommendUser.setUserId(2L);
                recommendUser.setScore(95D);
           }
        //获取该用户的详细信息
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());

        //构造返回值
        RecommendUserVO vo = new RecommendUserVO();
        BeanUtils.copyProperties(userInfo,vo);
        vo.setFateValue(recommendUser.getScore().intValue());
        if (userInfo.getTags()!=null){
            vo.setTags(userInfo.getTags().split(","));

        }
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity recommendation(RecommendUserQueryVO queryVO) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();

        //查询给userId推荐的好友 分页对象
        PageResult<RecommendUser> pageResult = recommendUserApi.recommendUserList(userId, queryVO.getPage(), queryVO.getPagesize());

        //如果没有查到 ，就设置默认值
        List<RecommendUser> recommendUserList = pageResult.getItems();
        if (recommendUserList==null||recommendUserList.size()==0){
            recommendUserList = new ArrayList<>();
            String ids="2,3,4,5,6,7,8,9,10,11";
            for (String id : ids.split(",")) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(id));
                recommendUser.setScore(RandomUtils.nextDouble(70,98));
                recommendUserList.add(recommendUser);
            }
               pageResult=new PageResult<>(10,queryVO.getPagesize(),1,queryVO.getPage(),recommendUserList);
        }
        //4.转换成RecommendUserVO列表
        List<RecommendUserVO> voList = new ArrayList<>();
        for (RecommendUser recommendUser : pageResult.getItems()) {
            //查询推荐用户的UserInfo
            UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
            //转换成RecommendUserVo
            RecommendUserVO vo = new RecommendUserVO();
            BeanUtils.copyProperties(userInfo,vo);
            if (userInfo.getTags()!=null){
                vo.setTags(userInfo.getTags().split(","));
            }
            //设置缘分值
            vo.setFateValue(recommendUser.getScore().intValue());
            //存储到voList里
            voList.add(vo);
        }
        //构造返回值
        PageResult<RecommendUserVO> voResult = new PageResult<>();
        BeanUtils.copyProperties(pageResult,voResult);
         voResult.setItems(voList);
         return ResponseEntity.ok(voResult);


    }
   //交友---查看佳人信息
    public ResponseEntity findPersonalInfo(Long targetUserId) {
        //查看佳人详细信息
        UserInfo userInfo = userInfoApi.findById(targetUserId);
        //查询当前用户和佳人的缘分值
        Long score = recommendUserApi.findRecommendScore(targetUserId, UserHolder.getUserId());
        //封装结果
        RecommendUserVO vo = new RecommendUserVO();
        BeanUtils.copyProperties(userInfo,vo);
        vo.setTags(userInfo.getTags().split(","));
        vo.setFateValue(score.intValue());
        return ResponseEntity.ok(vo);
    }

    //交友--查看陌生人问题
    public ResponseEntity findStrangerQuestion(Long targetUserId) {
        Question question = questionApi.findByUserId(targetUserId);
     if (question==null){
         return ResponseEntity.ok("你喜欢我吗？");
     }
        return ResponseEntity.ok(question.getTxt());
    }
//交友--回复陌生人问题
    public ResponseEntity replyStrangerQuestion(Long targetUserId, String reply) {
        //获取当前用户的详细信息
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());

        //获取对方的陌生人问题
        Question question = questionApi.findByUserId(targetUserId);
        String questionTxt=question==null?"你喜欢我吗":question.getTxt();
        //封装信息对象
        IMessage message = new IMessage();
        message.setUserId(UserHolder.getUserId().toString());
        message.setNickname(userInfo.getNickname());
        message.setReply(reply);
        //调用环信api 给用户发送消息（回复陌生人问题）
         huanXinTemplate.sendMsg(targetUserId.toString(),message);

        return ResponseEntity.ok(null);
    }

    /**
     * 探花-搜附近
     * GET /tanhua/search
     */
    public ResponseEntity searchNear(String gender, Integer distance) {
        //1. 获取当前用户id
        Long userId = UserHolder.getUserId();
        //2. 调用API，搜索附近的人
        List<UserLocationDTO> locationDTOList = userLocationApi.searchNear(userId, distance);
        //3. 转换成VO，并排除性别不符合的人
        List<NearUserVO> voList = new ArrayList<>();
        for (UserLocationDTO userLocation : locationDTOList) {
            //排除自己
            if (userId.intValue() == userLocation.getUserId()) {
                continue;
            }

            //查找附近的人的详细信息
            UserInfo userInfo = userInfoApi.findById(userLocation.getUserId());
            //排除性别不符合的人
            if (!gender.equals(userInfo.getGender())) {
                continue;
            }

            NearUserVO vo = new NearUserVO();
            vo.setUserId(userInfo.getId());
            vo.setAvatar(userInfo.getAvatar());
            vo.setNickname(userInfo.getNickname());
            voList.add(vo);
        }

        return ResponseEntity.ok(voList);
    }
    }

